/*
轻量级存储: https://pub.flutter-io.cn/packages/shared_preferences
支持平台: Android iOS Linux macOS Web Windows
依赖:
dependencies:
  shared_preferences: ^2.1.1
引入:
import 'package:shared_preferences/shared_preferences.dart';
 */

import 'package:shared_preferences/shared_preferences.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';


/*
https://pub-web.flutter-io.cn/packages/shared_preferences

 */

abstract class XSharePreferencesUtils{

  static SharedPreferences? sharedPreferences;

  //1.在application中初始化
  static Future<bool> init() async{
    //等同:
    // if(sharedPreferences==null){
    //   sharedPreferences = await SharedPreferences.getInstance();
    // }
    sharedPreferences ??= await SharedPreferences.getInstance();
    //XLogUtils.printLog('---sharedPreferences init ok');
    return Future<bool>.value(true);
  }

  /*
  获得成功通知
  saveString().then(bool value){
  //...
  }
   */
  static Future<bool> saveString(String key,String value) async{
    if(sharedPreferences!=null){
      return await sharedPreferences!.setString(key, value);
    }
    XLogUtils.printLog('---sharedPreferences==null');
    return Future<bool>.value(false);
  }
  static Future<bool> saveDouble(String key,double value) async{
    if(sharedPreferences!=null){
      return await sharedPreferences!.setDouble(key, value);
    }
    XLogUtils.printLog('---sharedPreferences==null');
    return Future<bool>.value(false);
  }
  static Future<bool> saveBool(String key,bool value) async{
    if(sharedPreferences!=null){
      return await sharedPreferences!.setBool(key, value);
    }
    XLogUtils.printLog('---sharedPreferences==null');
    return Future<bool>.value(false);
  }
  static Future<bool> saveInt(String key,int value) async{
    if(sharedPreferences!=null){
      return await sharedPreferences!.setInt(key, value);
    }
    XLogUtils.printLog('---sharedPreferences==null');
    return Future<bool>.value(false);
  }

  static bool getBool(String key,{bool defaultValue=false}) {
    return sharedPreferences?.getBool(key)??defaultValue;
  }
  static double getDouble(String key,{double defaultValue=0.0}){
    return sharedPreferences?.getDouble(key)??defaultValue;
  }
  static String getString(String key){
    return sharedPreferences?.getString(key)??'';
  }
  static int getInt(String key,{int defaultValue=0}){
    return sharedPreferences?.getInt(key)??defaultValue;
  }

  /*
  删除: sharedPreferences?.remove(key);
  清空: sharedPreferences?.clear();
   */

}
